package com.sample.business.services.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sample.business.domain.entities.Authentication;
import com.sample.business.domain.entities.User;
import com.sample.business.services.UserManagementService;
import com.sample.dal.providers.UsersDataProvider;

@Service
public class UserManagementServiceImpl implements UserManagementService {

	private static final Logger LOG = LoggerFactory.getLogger(UserManagementServiceImpl.class);

	@Autowired
	private UsersDataProvider dataProvider;

	@Override
	public void updatePassword(String login, String oldPassword, String newPassword) {
		Authentication auth = dataProvider.getAuth(login);

		if (auth == null) {
			LOG.warn(String.format("Can't find authentication data by login %s", login));
			return;
		}

		if (StringUtils.equals(auth.getPassword(), oldPassword)) {
			auth.setPassword(newPassword);
			dataProvider.updateAuth(auth);
		} else {
			throw new IllegalArgumentException("Old password doesn't match");
		}
	}

	@Override
	public List<User> getAllUsers() {
		return dataProvider.getUsers();
	}

}
